package com.sls.web.manager.game.service.impl;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sls.core.common.CommonUtil;
import com.sls.core.socket.Head;
import com.sls.core.socket.SocketDTO;
import com.sls.core.socket.TransmissionCode;
import com.sls.web.manager.common.Constants;
import com.sls.web.manager.execption.ManagerException;
import com.sls.web.manager.game.pojo.Tencent;
import com.sls.web.manager.game.pojo.tencent.TencentLoginInfo;
import com.sls.web.manager.game.querybean.TencentQuery;
import com.sls.web.manager.game.service.TencentService;
import com.sls.web.manager.page.Pagination;
import com.sls.web.manager.pojo.UserInfoVO;
import com.sls.web.manager.socket.SuperService;

@Repository("tencentService")
public class TencentServiceImpl extends SuperService implements TencentService {
	private static Logger log = Logger.getLogger(TencentServiceImpl.class);
	private Gson gson;

	public TencentServiceImpl() {
		gson = CommonUtil.gson();
	}

	@Override
	public boolean confirmAudit(String supplierId, int priceRatio,
			UserInfoVO userInfoVO) throws Exception {
		Head head = new Head();
		head.setRequestId(UUID.randomUUID().toString());
		head.setServiceCode(Constants.TENCENT_AUDIT);
		head.setIp(userInfoVO.getCurrentIp());
		head.setUserId(userInfoVO.getUserId());
		Tencent tencent = new Tencent();
		tencent.setSupplierId(supplierId);
		tencent.setPriceRatio(priceRatio);
		tencent.setOperator(userInfoVO.getUserName());
		SocketDTO dto = super.send(head, tencent);
		if (dto != null
				&& dto.getHead() != null
				&& TransmissionCode.SUCCESS.getCode().equals(
						dto.getHead().getResponseCode())) {
			return true;
		} else {
			throw new ManagerException(dto.getHead().getResponseMessage());
		}
	}

	@Override
	public Pagination<Tencent> queryTencent(TencentQuery tencentQuery,
			UserInfoVO userInfoVO) throws Exception {
		log.info("当前用户：" + userInfoVO.getUserId()
				+ "，Enter TencentService queryTencent method...");
		Head head = new Head();
		head.setRequestId(UUID.randomUUID().toString());
		head.setServiceCode(Constants.TENCENT_PAGE_QUERY);
		head.setIp(userInfoVO.getCurrentIp());
		head.setUserId(userInfoVO.getUserId());
		SocketDTO socketDTO = super.send(head, tencentQuery);
		if (socketDTO != null
				&& socketDTO.getHead() != null
				&& TransmissionCode.SUCCESS.getCode().equals(
						socketDTO.getHead().getResponseCode())) {
			String body = socketDTO.getBody();
			Pagination<Tencent> tencent = gson.fromJson(body,
					new TypeToken<Pagination<Tencent>>() {
					}.getType());
			log.info("当前用户：" + userInfoVO.getUserId()
					+ "，Leave TencentService queryTencent method...");
			return tencent;
		} else {
			throw new ManagerException(socketDTO.getHead().getResponseMessage());
		}

	}

	@Override
	public Tencent queryTencentByGoodsId(String goodsId, UserInfoVO userInfoVO)
			throws Exception {
		log.info("当前用户：" + userInfoVO.getUserId()
				+ "，Enter TencentService queryTencentByName method...");
		Head head = new Head();
		head.setRequestId(UUID.randomUUID().toString());
		head.setServiceCode(Constants.TENCENT_QUERY_BY_NAME);
		head.setIp(userInfoVO.getCurrentIp());
		head.setUserId(userInfoVO.getUserId());
		Tencent tencent = new Tencent();
		tencent.setGoodsId(goodsId);
		SocketDTO dto = super.send(head, tencent);
		if (dto != null
				&& dto.getHead() != null
				&& TransmissionCode.SUCCESS.getCode().equals(
						dto.getHead().getResponseCode())) {
			log.info("服务端返回的信息为：" + dto.getBody());
			Tencent tencent2 = gson.fromJson(dto.getBody(), Tencent.class);
			log.info("当前用户：" + userInfoVO.getUserId()
					+ "，Leave TencentService queryTencentByName method...");
			return tencent2;
		} else {
			throw new ManagerException(dto.getHead().getResponseMessage());
		}
	}

	@Override
	public boolean addTencent(Tencent tencent, UserInfoVO userInfoVO)
			throws Exception {
		Head head = new Head();
		head.setRequestId(UUID.randomUUID().toString());
		head.setServiceCode(Constants.SAVE_TENCENT_PRODUCT);
		head.setIp(userInfoVO.getCurrentIp());
		head.setUserId(userInfoVO.getUserId());
		SocketDTO dto = super.send(head, tencent);
		if (dto != null
				&& dto.getHead() != null
				&& TransmissionCode.SUCCESS.getCode().equals(
						dto.getHead().getResponseCode())) {
			log.info("服务器返回信息：" + dto.getBody());
			return true;
		} else {
			throw new ManagerException(dto.getHead().getResponseMessage());
		}
	}

	@Override
	public Tencent queryOrder(Tencent tencent, UserInfoVO userInfoVO)
			throws Exception {
		Head head = new Head();
		head.setRequestId(UUID.randomUUID().toString());
		head.setServiceCode(Constants.TENCENT_ORDER_QUERY);
		head.setIp(userInfoVO.getCurrentIp());
		head.setUserId(userInfoVO.getUserId());
		SocketDTO dto = super.send(head, tencent);
		if (dto != null
				&& dto.getHead() != null
				&& TransmissionCode.SUCCESS.getCode().equals(
						dto.getHead().getResponseCode())) {
			if (StringUtils.isNotEmpty(dto.getBody())) {
				Tencent tencent2 = gson.fromJson(dto.getBody(), Tencent.class);
				return tencent2;
			}
			return null;
		} else {
			throw new ManagerException(dto.getHead().getResponseMessage());
		}
	}

	@Override
	public boolean updateTencent(Tencent tencent, UserInfoVO userInfoVO)
			throws Exception {
		Head head = new Head();
		head.setRequestId(UUID.randomUUID().toString());
		head.setServiceCode("020937");
		head.setIp(userInfoVO.getCurrentIp());
		head.setUserId(userInfoVO.getUserId());
		SocketDTO dto = super.send(head, tencent);
		if (dto != null
				&& dto.getHead() != null
				&& TransmissionCode.SUCCESS.getCode().equals(
						dto.getHead().getResponseCode())) {
			log.info("服务器返回信息：" + dto.getBody());
			return true;
		} else {
			throw new ManagerException(dto.getHead().getResponseMessage());
		}
	}

	/**
	 * 获取验证码
	 * 
	 * @param path
	 * @param fileName
	 * @param userInfoVO
	 */
	@Override
	public void saveExtraCode(String loginAccount, String path,
			String fileName, UserInfoVO userInfoVO) {
		byte[] array = queryExtraCodeStream(loginAccount, userInfoVO);
		try {
			ByteArrayInputStream is = new ByteArrayInputStream(array);
			File outFile = new File(path + "/extraCode/" + fileName);
			OutputStream os = new FileOutputStream(outFile);
			byte[] buff = new byte[1024];
			while (true) {
				int readed = is.read(buff);
				if (readed == -1) {
					break;
				}
				byte[] temp = new byte[readed];
				System.arraycopy(buff, 0, temp, 0, readed);
				os.write(temp);
			}
			is.close();
			os.close();
		} catch (Exception e) {
			log.error("获取验证码异常：", e);
		}
	}

	/**
	 * 获取验证码流
	 * 
	 * @param userInfoVO
	 * @return
	 */
	private byte[] queryExtraCodeStream(String loginAccount,
			UserInfoVO userInfoVO) {
		Head head = new Head();
		head.setRequestId(UUID.randomUUID().toString());
		head.setServiceCode("030600");
		head.setIp(userInfoVO.getCurrentIp());
		head.setUserId(userInfoVO.getUserId());
		TencentLoginInfo login = new TencentLoginInfo();
		login.setAcctName(loginAccount);

		SocketDTO dto = super.send(head, login);
		if (dto != null
				&& dto.getHead() != null
				&& TransmissionCode.SUCCESS.getCode().equals(
						dto.getHead().getResponseCode())) {
			String body = dto.getBody();
			if (StringUtils.isNotEmpty(body)) {
				byte[] array = gson.fromJson(body, byte[].class);
				log.info("byte[] array " + Arrays.toString(array));
				return array;
			}
			return null;
		} else {
			throw new ManagerException(dto.getHead().getResponseMessage());
		}
	}

	/**
	 * 腾讯登录
	 * 
	 * @param loginAccount
	 * @param extraCode
	 * @param passwordKey
	 * @param userInfoVO
	 * @throws Exception
	 */
	@Override
	public TencentLoginInfo loginTencent(String loginAccount, String extraCode,
			String passwordKey, UserInfoVO userInfoVO) throws Exception {
		Head head = new Head();
		head.setRequestId(UUID.randomUUID().toString());
		head.setServiceCode("030601");
		head.setIp(userInfoVO.getCurrentIp());
		head.setUserId(userInfoVO.getUserId());

		TencentLoginInfo login = new TencentLoginInfo();
		login.setAcctName(loginAccount);
		login.setExtraCode(extraCode);
		login.setPasswordKey(passwordKey);
		SocketDTO dto = super.send(head, login);
		if (dto != null
				&& dto.getHead() != null
				&& TransmissionCode.SUCCESS.getCode().equals(
						dto.getHead().getResponseCode())) {
			TencentLoginInfo te = gson.fromJson(dto.getBody(),
					TencentLoginInfo.class);
			return te;
		} else {
			throw new ManagerException(dto.getHead().getResponseMessage());
		}
	}

}
